//
// Created by T on 2018/11/14.
//

#ifndef __X_TIME_H__
#define __X_TIME_H__

#include <time.h>
#include "stm32f1xx.h"

#define DURATION_MILLISECOND    1
#define DURATION_SECOND         (DURATION_MILLISECOND * 1000)
#define DURATION_MINUTE         (DURATION_SECOND * 60)
#define DURATION_HOUR           (DURATION_MINUTE * 60)

typedef struct timev {
    time_t  tv_sec;  /* seconds */
    int32_t tv_msec; /* and milliseconds */
} timev_t;


#define	timeclear(tvp)		((tvp)->tv_sec = (tvp)->tv_msec = 0)
#define	timeisset(tvp)		((tvp)->tv_sec || (tvp)->tv_msec)
#define	timecmp(tvp, uvp, cmp)						\
	(((tvp)->tv_sec == (uvp)->tv_sec) ?				\
	    ((tvp)->tv_msec cmp (uvp)->tv_msec) :			\
	    ((tvp)->tv_sec cmp (uvp)->tv_sec))
#define	timeadd(tvp, uvp, vvp)						\
	do {								\
		(vvp)->tv_sec = (tvp)->tv_sec + (uvp)->tv_sec;		\
		(vvp)->tv_msec = (tvp)->tv_msec + (uvp)->tv_msec;	\
		if ((vvp)->tv_msec >= DURATION_SECOND) {		\
			(vvp)->tv_sec++;				\
			(vvp)->tv_msec -= DURATION_SECOND;		\
		}							\
	} while (0)
#define	timesub(tvp, uvp, vvp)						\
	do {								\
		(vvp)->tv_sec = (tvp)->tv_sec - (uvp)->tv_sec;		\
		(vvp)->tv_msec = (tvp)->tv_msec - (uvp)->tv_msec;	\
		if ((vvp)->tv_msec < 0) {				\
			(vvp)->tv_sec--;				\
			(vvp)->tv_msec += DURATION_SECOND;		\
		}							\
	} while (0)
#define timevaddmsec(tvp, msec, vvp) \
    do { \
        (vvp)->tv_sec = (tvp)->tv_sec + (msec) / 1000; \
        (vvp)->tv_msec = (tvp)->tv_msec + (msec) % 1000; \
        if ((vvp)->tv_msec >= 1000) { \
            ++(vvp)->tv_sec; \
            (vvp)->tv_msec -= 1000; \
        } \
    } while (0)

time_t gettimeseconds(time_t *t);
void gettimev(struct timev *tv);
void settimev(struct timev *tv);

#endif //__X_TIME_H__
